using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Security;
using System.Web;
using System.Xml;
using System.IO;

namespace Radev.Twitter
{
    public class Twitter
    {
        private string userName;

        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        private string password;

        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        private string baseURL = "http://twitter.com/statuses/";

        public string BaseURL
        {
            get { return baseURL; }
            set { baseURL = value; }
        }

        public Twitter()
        {
        }
        
        public Twitter( string userName, string password )
        {
            this.userName = userName;
            this.password = password;
        }

        public bool UpdateStatus( string status )
        {
            return Post( string.Format( "update.xml?status={0}", HttpUtility.UrlEncode( status ) ) );
        }

        public string GetStatus()
        {
            XmlDocument statusXML = new XmlDocument();
            statusXML.LoadXml(Get(string.Format("user_timeline/{0}.xml?count=1", userName)));
            return statusXML.GetElementsByTagName( "text" )[ 0 ].InnerText;
        }

        private bool Post( string url )
        {
            HttpWebRequest r = CreateRequest( baseURL + url );

            r.Method = "POST";
            r.ContentType = "application/x-www-form-urlencoded";
            
            HttpWebResponse response = r.GetResponse() as HttpWebResponse;

            return response.StatusCode == HttpStatusCode.OK ? true : false;
        }

        private string Get( string url )
        {
            HttpWebRequest r = CreateRequest( BaseURL + url );
            r.Method = "GET";

            HttpWebResponse response = r.GetResponse() as HttpWebResponse;

            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

        private HttpWebRequest CreateRequest( string url )
        {
            HttpWebRequest r = WebRequest.Create( url ) as HttpWebRequest;
            r.Credentials = new NetworkCredential( userName, password );

            return r;
        }
    }
}
